(function() {
    'use strict';

    angular.module('weApp.controllers')

            /**
             * 查询结果展示页面
             * @param  {[type]} $scope                 [description]
             * @param  {[type]} $rootScope             [description]
             * @param  {[type]} $state                 [description]
             * @param  {[type]} $timeout               [description]
             * @param  {[type]} $http                  [description]
             * @param  {[type]} weAppDataBase          [description]
             * @param  {[type]} $ionicPopup            [description]
             * @param  {[type]} $compile               [description]
             * @param  {[type]} showLinePageService){                                  }] [description]
             * @return {[type]}                        [description]
             */
            .controller('searchResCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', 'showLinePageService', 'localStorageService', 'myFavorsService',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, showLinePageService, localStorageService, myFavorsService) {
                    $scope.searchKeywords = $stateParams.searchText;
                    if ($scope.searchKeywords) {
                        localStorageService.set("searchKeywords", $scope.searchKeywords);
                    } else {
                        $scope.searchKeywords = localStorageService.get("searchKeywords");
                    }

                    // console.log( $scope.searchKeywords );

                    //站点线路查询URL
                    var searchUrl = $rootScope.rootLocation + "/line/station/search";

                    //获取附近站点参数配置
                    var req = {
                        method: 'post',
                        url: searchUrl,
                        data: {
                            "stationLineName": $scope.searchKeywords,
                            "cityCode": $rootScope.cityCode,
                            "cityName": $rootScope.cityName
                        }
                    };


                    $http(req)
                            .then(function(result) {

                                // console.log( result );

                                $scope.station = result.data.data;
                                $rootScope.stations = result.data.data.lineStations;
                                if ($scope.station == undefined)
                                    return;

                                if ($scope.station.lineStations.length) {

                                    //重构数据
                                    //这里根据上下行重构起止时间
                                    var stationLines = $scope.station.lineStations;
                                    for (var j = 0, jLen = stationLines.length; j < jLen; j++) {
                                        var line = stationLines[j];
                                        //默认值为上行
                                        line.evalStartBusTime = line.firstBusTime;
                                        line.evalEndBusTime = line.lastBusTime;
                                        //下行替换
                                        if (line.lineType === 2) {
                                            if (angular.isUndefined(line.downFirstBusTime) || angular.isUndefined(line.downLastBusTime)) {
                                                line.evalStartBusTime = line.firstBusTime;
                                                line.evalEndBusTime = line.lastBusTime;
                                            } else {
                                                line.evalStartBusTime = line.downFirstBusTime.trimSpace() == "" ? line.firstBusTime : line.downFirstBusTime;
                                                line.evalEndBusTime = line.downLastBusTime.trimSpace() == "" ? line.lastBusTime : line.downLastBusTime;
                                            }

                                        }
                                    }

                                    /**
                                     * 将真正可以查询到结果的用户搜索条件插入到 搜索历史中。
                                     * @type {[type]}
                                     */
                                    if ($.trim($scope.searchKeywords) != "") {
                                        $scope.searchHistory = localStorageService.get("searchHistory") == null ? [] : JSON.parse(localStorageService.get("searchHistory"));
                                        if ($scope.searchHistory.indexOf($scope.searchKeywords) == -1) {
                                            $scope.searchHistory.push($scope.searchKeywords);
                                            localStorageService.set("searchHistory", JSON.stringify($scope.searchHistory));
                                        }
                                    }


                                    if (localStorageService.get("myFavors") !== null && localStorageService.get("myFavorsJSON") !== null) {
                                        $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                                        $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                                    } else {
                                        //如果没有任何收藏数据，则直接存入浏览器空数据
                                        localStorageService.set("myFavors", null);
                                        localStorageService.set("myFavorsJSON", null);
                                    }

                                }

                            });

                    /**
                     * 页面每次进入时读取一下本地收藏
                     * @param  {[type]} event [description]
                     * @param  {[type]} data  ){                      $scope.myFavors [description]
                     * @return {[type]}       [description]
                     */
                    $scope.$on("$ionicView.beforeEnter", function(event, data) {
                        $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                    });


                    /**
                     * 点击后将该线路加入本地收藏
                     * 收藏的数据将会被存入本地浏览器的LocalStorage中
                     * @param  {[type]} line  [line JSON Data]
                     * @param  {[type]} event [click event]
                     */
                    $scope.favorLine = function(line, event) {
                        //当前点击的lineID;
                        var stationId = line.lineStationId;
                        //如果当前myFavors数组总不含有当前点击的lineID
                        //意为当前点击的线路并未被收藏则执行收藏操作
                        if ($scope.myFavors == null)
                            $scope.myFavors = [];
                        if ($scope.myFavors.indexOf(stationId) == -1) {
                            //通过服务存入LocalStorage
                            myFavorsService.set(line);
                            //存入当前页面临时数组中
                            $scope.myFavors.push(stationId);
                            $scope.tipShown = true;
                            $scope.tipContent = '收藏成功';

                        } else {    //移除操作
                            //通过服务移除LocalStorage中的当前线路
                            myFavorsService.remove(line);
                            //移除临时数组中的ID
                            $scope.myFavors.remove(stationId);
                            $scope.tipShown = true;
                            $scope.tipContent = '取消收藏成功';
                        }

                    }

                    $scope.showLine = function(line, event, params) {
                        if (angular.element(event.target).hasClass('station-favor') || angular.element(event.target).hasClass('we-font'))
                            return;
                        showLinePageService.gotoLinePage(line, event, {searchText: $scope.searchKeywords});
                    }

                    $scope.backToIndex = function() {
                        // console.log( $rootScope.prevState.name );
                        if ($rootScope.prevState.name) {
                            $state.go('search');
                        } else {
                            $state.go('index');
                        }

                    }


                }])

})();